#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->btn_analysis,&QPushButton::clicked,this,&MainWindow::m_on_btn_analysis_clicked);
    connect(ui->btn_save,&QPushButton::clicked,this,&MainWindow::m_on_btn_save_clicked);
    connect(ui->tbtn_choseFile,&QToolButton::clicked,this,&MainWindow::m_on_tbtn_choseFile_clicked);


}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::m_on_btn_analysis_clicked()
{
    // 1. 读取文件内容到 QByteArray
    QFile file(ui->le_filePath->text());
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "{异常}无法打开文件";
        return;
    }
    QByteArray jsonData = file.readAll();
    file.close();

    // 2. 使用 QJsonDocument::fromJson() 解析
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &parseError);

    if (jsonDoc.isNull())
    {
        qDebug() << "{异常}解析失败" << parseError.errorString();
        return;
    }

    // 3. 检查根是否是对象，并获取 QJsonObject
    if (jsonDoc.isObject())
    {
        QString retract[] = {"", "    ", "        "};

        QJsonObject rootObject = jsonDoc.object();
        // 4. 从 QJsonObject 中获取值，并且显示在QTextEdit上
        ui->te_analysis_after->clear();
        ui->te_analysis_after->append(QString("projectId = %1").arg(rootObject["projectId"].toInt()));
        ui->te_analysis_after->append(QString("projectName = %1").arg(rootObject["projectName"].toString()));
        ui->te_analysis_after->append(QString("isCompleted = %1").arg(rootObject["isCompleted"].toBool()));
        ui->te_analysis_after->append(QString("completionPercentage = %1").arg(rootObject["completionPercentage"].toDouble()));
        ui->te_analysis_after->append(QString("startDate = %1").arg(rootObject["startDate"].toString()));

        {
            QJsonObject object1 = rootObject["manager"].toObject();
            ui->te_analysis_after->append(retract[0] + "manager{");
            ui->te_analysis_after->append(retract[1] + QString("name = %1").arg(object1["name"].toString()));
            ui->te_analysis_after->append(retract[1] + QString("employeeId = %1").arg(object1["employeeId"].toString()));
            {
                QJsonObject object2 = object1["contact"].toObject();
                ui->te_analysis_after->append(retract[1] + "contact{");
                ui->te_analysis_after->append(retract[2] + QString("phone = %1").arg(object2["phone"].toString()));
                ui->te_analysis_after->append(retract[2] + QString("email = %1").arg(object2["email"].toString()));
                ui->te_analysis_after->append(retract[1] + "}");
            }
            ui->te_analysis_after->append(retract[0] + "}");
        }


        QJsonArray jsonArray1 = rootObject["tasks"].toArray();
        ui->te_analysis_after->append(retract[0] + "tasks[");
        for(const auto& value : jsonArray1)
        {
            ui->te_analysis_after->append(retract[1] + value.toString());
        }
        ui->te_analysis_after->append(retract[0] + "]");

        QJsonArray jsonArray2 = rootObject["team"].toArray();
        ui->te_analysis_after->append(retract[0] + "team[");
        for(const auto& value : jsonArray2)
        {
            QJsonObject object1 = value.toObject();
            ui->te_analysis_after->append(retract[1] + "{");
            ui->te_analysis_after->append(retract[2] + QString("memberId = %1").arg(object1["memberId"].toString()));
            ui->te_analysis_after->append(retract[2] + QString("name = %1").arg(object1["name"].toString()));
            ui->te_analysis_after->append(retract[2] + QString("role = %1").arg(object1["role"].toString()));
            ui->te_analysis_after->append(retract[2] + QString("isLead = %1").arg(object1["isLead"].toBool()));
            ui->te_analysis_after->append(retract[1] + "}");
        }
        ui->te_analysis_after->append(retract[0] + "]");

        if(rootObject["reviewers"].isNull())
            ui->te_analysis_after->append("reviewers = 值是空的");
        else
            ui->te_analysis_after->append("reviewers = 值是非空的");
    }
}

void MainWindow::m_on_btn_save_clicked()
{
    // 1. 构建一个 QJsonObject
    QJsonObject rootJson;
    rootJson["projectId"] = 101;
    rootJson["projectName"] = "Mobile App Redesign";
    rootJson["isCompleted"] = false;
    rootJson["completionPercentage"] = 0.75;
    rootJson["startDate"] = "2025-08-01";

    {
        QJsonObject object1;
        object1["name"] = "Alice Johnson";
        object1["employeeId"] = "MJ456";
        {
            QJsonObject object2;
            object2["phone"] = "555-1234";
            object2["email"] = "alice@company.com";
            object1["contact"] = object2;
        }
        rootJson["manager"] = object1;
    }
    // 2. 构建一个 QJsonArray
    QJsonArray array1;
    array1.append("UI/UX Design");
    array1.append("Frontend Development");
    array1.append("Backend Development");
    array1.append("Database Setup");
    array1.append("Testing");

    rootJson["tasks"] = array1;

    QJsonArray array2;
    {
        QJsonObject object1;
        object1["memberId"] = "TM001";
        object1["name"] = "Bob Smith";
        object1["role"] = "Frontend";
        object1["isLead"] = true;
        array2.append(object1);
        object1["memberId"] = "TM002";
        object1["name"] = "Charlie Brown";
        object1["role"] = "Backend";
        object1["isLead"] = false;
        array2.append(object1);
        object1["memberId"] = "TM003";
        object1["name"] = "David Wilson";
        object1["role"] = "UI/UX";
        object1["isLead"] = false;
        array2.append(object1);
    }

    rootJson["team"] = array2;

    // 3. 将 QJsonObject 放入 QJsonDocument
    QJsonDocument jsonDoc(rootJson);

    // 4. 将 QJsonDocument 转换成 QByteArray
    QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Indented); // QJsonDocument::Indented 可以让输出格式化，更易读

    // 5. 写入文件
    QString filePath = QFileDialog::getSaveFileName(this,
                                                    "选择将JSON文件保存到什么位置",
                                                    "../../testJson/testOut.json",
                                                    "JSON(*.json)");
    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly))
    {
        file.write(jsonData);
        file.close();
        qDebug() << "文件写入成功！";
    }
}

void MainWindow::m_on_tbtn_choseFile_clicked()
{
    QString fileInfo = QFileDialog::getOpenFileName(this,
                                                    "选择要解析的Json文件",
                                                    "../../testJSON/",
                                                    "JSON/XML(*.json *.XML);;Database(*.db)");
    ui->le_filePath->setText(fileInfo);
}
